package com.hello.pet.config.security;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.hello.pet.service.system.dto.WxAuthDto;
import com.hello.pet.service.system.model.User;
import com.hello.pet.service.system.param.UserParam;
import com.hello.pet.service.system.param.WxLoginParam;
import com.hello.pet.service.system.service.UserService;
import com.hello.pet.service.system.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 身份验证提供者
 */
@Component
public class WxAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private WxUtil wxUtil;

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //认证微信用户
        WxLoginParam wxLoginParam  = (WxLoginParam)authentication.getPrincipal();
        WxAuthDto wxAuthDto = wxUtil.getWxKeyAndOpenId(wxLoginParam.getCode());
        //处理user
        User userByOpenId = userService.findByOpenId(wxAuthDto.getOpenId());
        User user = wxLoginParam.getUser();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        String name = "";
        if (BeanUtil.isNotEmpty(userByOpenId)){
            //非首次登录-更新userInfo
            userByOpenId.setUpdateTime(LocalDateTime.now());
            userByOpenId.setGender(user.getGender());
            userByOpenId.setHeadPortrait(user.getHeadPortrait());
            grantedAuthorities = userService.findPermissions(userByOpenId.getName()).stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
            userService.updateById(userByOpenId);
            name = userByOpenId.getName();
        }else{
            //首次登录-设置用户信息
            UserParam userParam = new UserParam();
            userParam.setName(user.getName()+RandomUtil.randomInt(1000, 9999));
            userParam.setGender(user.getGender());
            userParam.setHeadPortrait(user.getHeadPortrait());
            userService.addUser(userParam,wxAuthDto.getOpenId());
            name = userParam.getName();
        }
        //获取用户权限
        return new WxAuthenticatioToken(name,grantedAuthorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (WxAuthenticatioToken.class.isAssignableFrom(authentication));
    }
}